<?php

namespace app\admin\model;

use app\common\model\TimeModel;
use think\facade\Db;
use think\Model;

class SystemFinanceDay extends TimeModel
{

    protected $name = "system_finance_day";

    protected $deleteTime = false;

    private array $countField = [
        11 => 'user_consume',
        21 => 'user_refund',
        31 => 'cashcard_use',
    ];

    public static function onAfterRead(Model $model)
    {
        if(isset($model->date)){
            $model->date_ymd = date('Y-m-d',$model->date);
        }
    }


    /**
     * @title 更新统计数据
     * @param mixed $value
     * @param mixed $type
     * @author FashionJune
     */
    public function updateFinance($value, $type)
    {
        $today = strtotime('today');
        $today_record = $this->where(['date' => $today])->find();
        if (is_array($value)) {//多个要改变的值
            $save_data = [];
            foreach ($value as $k => $v) {
                if (isset($this->countField[$type[$k]])) {//id传入
                    $field = $this->countField[$type[$k]];
                } elseif(in_array($type[$k], $this->countField)) {//name传入
                    $field = $type[$k];
                } else {
                   continue;
                }
                $save_data[$field] = Db::raw($field . '+' . $v);
                $insert_data[$field] = $v;
            }
        } else {//单值改变
            if (isset($this->countField[$type])) {//id传入
                $field = $this->countField[$type];
            } elseif(in_array($type, $this->countField)) {//name传入
                $field = $type;
            } else {
                return false;
            }
            $save_data[$field] = Db::raw($field . '+' . $value);
            $insert_data[$field] = $value;
        }
        if ($today_record) {//更新
            $today_record->save($save_data);
        } else {//新增
            $insert_data['date'] = $today;
            $this->save($insert_data);
        }
    }


    public function createTestRecords(int $nums = 30){
        $prefix = env('database.prefix');
        $sql = 'truncate ' . $prefix . 'system_finance_day' . ';';
        Db::query($sql);
        $day = $today = strtotime('today');
        $insert_data = [];
        for ($i=1;$i<=$nums;$i++) {
            $insert_data[] = [
                'date' => $day,
                'cashcard_use' => random_int(100,999)/100,
                'user_recharge' => random_int(1000,9999)/100,
                'user_refund' => random_int(1000,9999)/100,
            ];
            $day -= 86400;
        }
        $this->saveAll($insert_data);
    }
    

}